<template>
  <!-- 面包屑 -->
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">仓储管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/GetIncominginformationView">采购入库</a>
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <!-- 入库信息搜索框 -->
  <div style="margin-top: 20px; width: 900px">
    <el-form :inline="true">
      <el-form-item label="入库单编号:">
        <el-input v-model="page.StorageNo" placeholder="请输入入库单编号" />
      </el-form-item>
      <el-form-item label="入库单名称:">
        <el-input v-model="page.StorageName" placeholder="请输入入库单名称" />
      </el-form-item>
      <el-form-item label="供应商名称:">
        <el-input v-model="page.SupplierName" placeholder="请输入供应商名称" />
      </el-form-item>
      <el-form-item label="订单编号:">
        <el-input
          v-model="page.StoragePurchaseNo"
          placeholder="请输入订单编号"
        />
      </el-form-item>
      <el-form-item label="入库时间:">
        <el-date-picker
          v-model="page.StorageDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getIncominginformation()"
          >搜索</el-button
        >
        <el-button type="primary" @click="empty()">清空</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!-- 显示 -->
  <div style="margin-top: 20px">
    <el-button type="primary" size="small" @click="open(null)">新增</el-button>
    <el-button type="warning" size="small" @click="GetExelRoomNumber"
      >导出</el-button
    >
    <el-button type="info" size="small" @click="ImportRoomNumber"
      >导入</el-button
    >
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column prop="storageNo" label="入库单编号" width="180">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="open(scope.row)">
            {{ scope.row.storageNo }}</el-button
          >
        </template>
      </el-table-column>
      <el-table-column prop="storageName" label="入库单名称" width="180" />
      <el-table-column prop="supplierName" label="供应商名称" width="180" />
      <el-table-column prop="storageDate" label="入库日期" width="180">
        <template #default="scope">
          {{ scope.row.storageDate.substring(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="storagePurchaseNo"
        label="采购订单号"
        width="180"
      />
      <el-table-column prop="noticePurchase" label="单据状态" width="180">
        <template #default="scope">
          
          {{
            scope.row.noticePurchase == 0 ?"待审批":
            scope.row.noticePurchase == 1
              ? "审批中"
              : scope.row.noticePurchase == 2
              ? "已审批"
              : scope.row.noticePurchase == 3
              ? "待上架"
              : "已完成"
          }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="scope">
          <!-- 修改删除按钮显示条件 -->
          <!--  <el-button
            v-if="scope.row.noticePurchase === 3"
            link
            type="success"
            size="small"
            @click=""
            >待入库</el-button
          > -->
          <!-- 待上架状态显示执行入库 -->
          <el-button
            v-if="scope.row.noticePurchase === 3"
            link
            type="primary"
            size="small"
            @click="executeInventory()"
            >执行入库</el-button
          >

          <!-- 已执行状态显示上架 -->
          <el-button
            v-if="scope.row.noticePurchase === 4"
            link
            type="success"
            size="small"
            @click="shelfInventory(scope.row.storageId)"
          ></el-button>
          <!-- 非完成状态显示常规操作 -->
          <template
            v-if="scope.row.noticePurchase !== 3 && scope.row.noticePurchase !== 4"
          >
            <el-button link type="primary" size="small" @click="open(scope.row)"
              >修改</el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="delIncoming(scope.row.storageId)"
              >删除</el-button
            >
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
        v-model:current-page="page.PageIndex"
        v-model:page-size="page.PageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>

  <!--采购入库  -->
  <el-dialog
    v-model="Eject.dialogFormVisible"
    :title="Eject.title"
    width="1000"
  >
    <!-- <el-form :model="form" :inline="true">
    、
      <el-form-item label="*入库单编号">
        <el-input
          v-model="form.storageNo"
          placeholder="请输入入库单编号"
          style="width: 300px"
        />
        <el-button type="primary" plain @click="generateNumber"
          >自动生成</el-button
        >
      </el-form-item> -->
    <el-form :model="form" :inline="true">
      <el-form-item label="入库单编号:" :label-width="Eject.formLabelWidth">
        <el-input
          v-model="form.storageNo"
          autocomplete="off"
          style="width: 180px; height: 30px"
          :readonly="form.autoGenerate"
          clearable
          @click.native="handleCodeClick"
        />
        <template slot="prepend">R</template>
        <el-switch
          width="40"
          v-model="form.autoGenerate"
          active-text="自动生成"
          active-color="#67C23A"
          @change="handleSwitchChange"
        />
      </el-form-item>
      <!-- 入库单名称 -->
      <el-form-item label="*入库单名称">
        <el-input
          v-model="form.storageName"
          placeholder="请输入入库单名称"
          style="width: 300px"
        />
      </el-form-item>
      <!-- 入库日期 -->
      <el-form-item label="*入库日期">
        <el-date-picker
          v-model="form.storageDate"
          type="date"
          placeholder="请选择到货日期"
        />
      </el-form-item>
      <!-- 到货通知单 -->
      <el-form-item label="到货通知单">
        <el-input
          v-model="selectedNoticeInfo.noticeNo"
          placeholder="请选择到货通知单"
          readonly
        >
          <template #append>
            <el-button icon="Search" @click="showNoticeDialog" />
          </template>
        </el-input>
      </el-form-item>

      <!-- 采购订单号 -->
      <el-form-item label="采购订单号">
        <el-input
          v-model="selectedNoticeInfo.storagePurchaseNo"
          readonly
          placeholder="请选择采购订单"
        />
      </el-form-item>
      <!-- 供应商名称 -->
      <el-form-item label="供应商名称">
        <el-input
          v-model="selectedNoticeInfo.supplierName"
          readonly
          placeholder="请选择供应商名称"
        >
          <template #append>
            <el-button icon="Search" @click="showsupplierlog" />
          </template>
        </el-input>
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注">
        <el-input
          v-model="form.storageremark"
          type="textarea"
          :rows="3"
          placeholder="请输入内容"
        />
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <template #footer>
      <el-button @click="Eject.noticeDialogVisible = false">关闭</el-button>
      <el-button type="primary" @click="sava()">保存</el-button>
    </template>

    <!-- 子对话框 -->
    <delivery-notice-dialog
      v-model:visible="Eject.noticeDialogVisible"
      @select="handleNoticeSelect"
    />
    <supplier-dialog
      v-model:visible="Eject.supplierDialogVisible"
      @select="handleSupplierSelect"
    />
  </el-dialog>

  <div>
    <el-dialog
      v-model="Eject.dialogupdataFormVisible"
      :title="Eject.title"
      width="1000"
    >
      <!-- 修改 -->
      <el-form :model="form" :inline="true">
        <!-- 入库单编号 -->
        <el-form-item label="*入库单编号">
          <el-input
            v-model="form.storageNo"
            placeholder="请输入入库单编号"
            style="width: 300px"
          />
          <el-button type="primary" plain @click="generateNumber"
            >自动生成</el-button
          >
        </el-form-item>

        <!-- 入库单名称 -->
        <el-form-item label="*入库单名称">
          <el-input
            v-model="form.storageName"
            placeholder="请输入入库单名称"
            style="width: 300px"
          />
        </el-form-item>
        <!-- 入库日期 -->
        <el-form-item label="*入库日期">
          <el-date-picker
            v-model="form.storageDate"
            type="date"
            placeholder="请选择到货日期"
          />
        </el-form-item>
        <!-- 到货通知单 -->
        <el-form-item label="到货通知单">
          <el-input
            v-model="selectedNoticeInfo.noticeNo"
            placeholder="请选择到货通知单"
            readonly
          >
            <template #append>
              <el-button icon="Search" @click="showNoticeDialog" />
            </template>
          </el-input>
        </el-form-item>

        <!-- 采购订单号 -->
        <el-form-item label="采购订单号">
          <el-input
            v-model="selectedNoticeInfo.storagePurchaseNo"
            readonly
            placeholder="请选择采购订单"
          />
        </el-form-item>
        <!-- 供应商名称 -->
        <el-form-item label="供应商名称">
          <el-input
            v-model="selectedNoticeInfo.supplierName"
            readonly
            placeholder="请选择供应商名称"
          >
            <template #append>
              <el-button icon="Search" @click="showsupplierlog" />
            </template>
          </el-input>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注">
          <el-input
            v-model="form.storageremark"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>

      <template #footer="scope">
        <el-button @click="Eject.noticeDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="updatasava()">保存</el-button>
        <el-button
          type="primary"
          size="small"
          @click="submint(form.storageId)"
          style="margin-right: 10px"
          >提交</el-button
        >
      </template>

      <!-- 操作按钮 -->

      <!-- 子对话框 -->
      <delivery-notice-dialog
        v-model:visible="Eject.noticeDialogVisible"
        @select="handleNoticeSelect"
      />
      <supplier-dialog
        v-model:visible="Eject.supplierDialogVisible"
        @select="handleSupplierSelect"
      />

      <!-- 物料信息 -->
      <div style="margin-top: 80px">
        <el-link
          type="primary"
          size="small"
          @click="showmateriDialog()"
          style="margin-left: 20px"
          >新增</el-link
        >
        <el-table :data="maters" style="width: 100%; margin-top: 10px">
          <el-table-column type="序号" width="55" />
          <el-table-column prop="materialnumber" label="物料编码" width="120" />
          <el-table-column prop="materialname" label="物料名称" width="120" />
          <el-table-column prop="specification" label="规格型号" width="120" />
          <el-table-column prop="unit" label="单位" width="120" />
          <el-table-column prop="inboundNumber" label="入库数量" width="120" />
          <el-table-column prop="lotnumber" label="批次号" width="120" />

          <el-table-column label="操作" min-width="120">
            <template #default="scope">
              <el-link type="primary" size="small" style="margin-right: 10px"
                >修改</el-link
              >
              <el-link type="primary" size="small" style="margin-right: 10px"
                >删除</el-link
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
  <!-- 到货通知单 -->
  <div>
    <el-dialog
      title="到货通知单"
      v-model="Eject.noticeDialogVisible"
      style="margin-right: 80px"
      width="1200px"
    >
      <!-- 搜索表单 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="通知单编号">
          <el-input
            v-model="searchForm.noticeNo"
            placeholder="请输入通知单编号"
          />
        </el-form-item>
        <el-form-item label="通知单名称">
          <el-input
            v-model="searchForm.noticeName"
            placeholder="请输入通知单名称"
          />
        </el-form-item>
        <el-form-item label="采购订单编号">
          <el-input
            v-model="searchForm.storagePurchaseNo"
            placeholder="请输入采购订单编号"
          />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input
            v-model="searchForm.supplierName"
            placeholder="请输入供应商名称"
          />
        </el-form-item>
        <el-form-item label="到货日期">
          <el-date-picker
            v-model="searchForm.deliverydate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select
            v-model="searchForm.noticePurchase"
            placeholder="请选择"
            style="width: 100px"
          >
            <el-option label="审批中" value="1" />
            <el-option label="已审批" value="2" />
            <el-option label="已确定" value="3" />
            <el-option label="已完成" value="4" />

            <!-- 其他状态选项 -->
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getnotices">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="noticeList" border style="width: 100%">
        <!-- 选择列 -->
        <!-- 单选列 -->
        <el-table-column label="选择" width="80" align="center">
          <template #default="{ row }">
            <!-- 修复1: 使用唯一标识符作为radio的value -->
            <el-radio
              v-model="selectedNoticeId"
              :label="row.noticeId"
              @change="handleNoticeSelect(row)"
            ></el-radio>
          </template>
        </el-table-column>

        <!-- 数据列 -->
        <el-table-column prop="noticeNo" label="入库单编号" width="180" />
        <el-table-column prop="noticeName" label="通知单名称" />
        <el-table-column
          prop="storagePurchaseNo"
          label="采购订单号"
          width="120"
        />
        <el-table-column prop="supplierName" label="供应商名称" width="220" />
        <el-table-column prop="contacts" label="联系人" width="120" />
        <el-table-column prop="contactway" label="联系方式" width="150" />
        <el-table-column prop="deliverydate" label="到货日期" width="120">
          <template #default="scope">
            {{ scope.row.deliverydate.substring(0, 10) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>

  <!-- 供应商 -->
  <div>
    <el-dialog
      title="供应商选择"
      v-model="Eject.supplierDialogVisible"
      style="margin-right: 80px"
      width="1200px"
    >
      <!-- 搜索表单 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="供应商编码">
          <el-input
            v-model="suppliers.SupplierNumber"
            placeholder="请输入供应商编码"
          />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input
            v-model="suppliers.SupplierName"
            placeholder="请输入供应商名称"
          />
        </el-form-item>
        <el-form-item label="供应商简介">
          <el-input
            v-model="suppliers.SupplierAbbreviation"
            placeholder="请输入供应商简介"
          />
        </el-form-item>
        <el-form-item label="供应商英文名">
          <el-input
            v-model="suppliers.SupplierEnglishName"
            placeholder="请输入供应商英文名"
          />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-select
            v-model="suppliers.IsEnable"
            placeholder="请选择"
            style="width: 100px"
          >
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getsuppliers()">搜索</el-button>
          <el-button @click="resetsuppliersSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="supplierList" border style="width: 100%">
        <!-- 选择列 -->
        <!-- 单选列 -->
        <el-table-column label="选择" width="80" align="center">
          <template #default="{ row }">
            <!-- 修复2: 使用唯一标识符作为radio的value -->
            <el-radio
              v-model="selectedSupplierId"
              :label="row.supplierId"
              @change="handleSupplierSelect(row)"
            ></el-radio>
          </template>
        </el-table-column>

        <!-- 数据列 -->
        <el-table-column prop="supplierNumber" label="供应商编码" width="180" />
        <el-table-column prop="supplierName" label="供应商名称" width="220" />
        <el-table-column
          prop="supplierAbbreviation"
          label="供应商简称"
          width="120"
        />
        <el-table-column
          prop="supplierEnglishName"
          label="供应商英文"
          width="150"
        />
      </el-table>
    </el-dialog>
  </div>

  <!-- 添加物料入库单行 -->
  <div>
    <el-dialog
      v-model="Eject.materiDialogVisible"
      title="添加物料入库单行"
      width="1000px" 
    >
      <el-form class="search-form" :inline="true">
        <el-form-item label="*物料编码" required>
          <el-input
            v-model="formData.materialnumber"
            placeholder="请选择物料编码"
            style="width: 200px; margin-right: 20px"
            readonly
          >
            <template #append>
              <el-button icon="Search" @click="showmaterialOptions" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="物料名称">
          <el-input
            v-model="formData.materialname"
            style="width: 200px"
            readonly
          />
        </el-form-item>

        <el-form-item label="单位">
          <el-input v-model="formData.unit" readonly />
        </el-form-item>

        <el-form-item label="入库数量" required>
          <el-input-number
            v-model="formData.inboundNumber"
        
            controls-position="right"
            
          />
        </el-form-item>

        <el-form-item label="生产日期">
          <el-date-picker
            v-model="formData.sTime"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>

        <el-form-item label="有效期">
          <el-date-picker
            v-model="formData.validityDate"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>

        <el-form-item label="批次号">
          <el-input v-model="formData.lotnumber" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            style="width: 800px; margin-left: 10px"
            maxlength="200"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="Eject.materiDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm()">确定</el-button>
      </template>
    </el-dialog>
  </div>

  <!-- 到货通知单选择--物料入库 Arrivalnotice-->
  <div>
    <el-dialog
      title="到货通知单选择"
      v-model="Eject.ArrivalnoticematerVisible"
      style="margin-right: 80px; text-align: center"
      width="1200px"
    >
      <!-- 数据表格 -->
      <el-table :data="materArriva" border style="width: 100%">
        <!-- 选择列 -->
        <!-- 单选列 -->
        <el-table-column label="选择" width="80" align="center">
          <template #default="{ row }">
            <!-- 修复2: 使用唯一标识符作为radio的value -->
            <el-radio
              v-model="selectedSupplierArrMateId"
              :label="row.noticeId"
              @change="handleArrivalnoticematerSelect(row)"
            ></el-radio>
          </template>
        </el-table-column>

        <!-- 数据列 -->
        <el-table-column prop="materialnumber" label="物料编码" width="180" />
        <el-table-column prop="materialname" label="物料名称" width="180" />
        <el-table-column prop="specification" label="规格型号" width="180" />
        <el-table-column prop="unit" label="单位" width="180" />
        <el-table-column prop="noticeNumber" label="到货数量" width="180" />
        <el-table-column prop="isInspecs" label="是否检验" width="180">
          <template #default="scope">
            {{ scope.row.isInspecs == 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column prop="qualifiedNum" label="合格数量" width="180" />
        <el-table-column prop="inspecNumber" label="检验单号" width="180" />
        <el-table-column prop="contactremark" label="备注" width="180" />
      </el-table>
    </el-dialog>
  </div>

  <!-- 执行入库 -->
  <div>
    <el-dialog
      v-model="Eject.dialogupdatacarryFormVisible"
      title="执行入库信息"
      width="1000"
    >
      <!-- 修改 -->
      <!--   <el-form :model="form" :inline="true">

        <el-form-item label="*入库单编号">
          <el-input
            v-model="form.storageNo"
            placeholder="请输入入库单编号"
            style="width: 300px"
          />
          <el-button type="primary" plain @click="generateNumber"
            >自动生成</el-button
          >
        </el-form-item>

     
        <el-form-item label="*入库单名称">
          <el-input
            v-model="form.storageName"
            placeholder="请输入入库单名称"
            style="width: 300px"
          />
        </el-form-item>
    
        <el-form-item label="*入库日期">
          <el-date-picker
            v-model="form.storageDate"
            type="date"
            placeholder="请选择到货日期"
          />
        </el-form-item>
      
        <el-form-item label="到货通知单">
          <el-input
            v-model="selectedNoticeInfo.noticeNo"
            placeholder="请选择到货通知单"
            readonly
          >
            <template #append>
              <el-button icon="Search" @click="showNoticeDialog" />
            </template>
          </el-input>
        </el-form-item>

      
        <el-form-item label="采购订单号">
          <el-input
            v-model="selectedNoticeInfo.storagePurchaseNo"
            readonly
            placeholder="请选择采购订单"
          />
        </el-form-item>
   
        <el-form-item label="供应商名称">
          <el-input
            v-model="selectedNoticeInfo.supplierName"
            readonly
            placeholder="请选择供应商名称"
          >
            <template #append>
              <el-button icon="Search" @click="showsupplierlog" />
            </template>
          </el-input>
        </el-form-item>

  
        <el-form-item label="备注">
          <el-input
            v-model="form.storageremark"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form> -->

      <template #footer="scope">
        <el-button @click="Eject.noticeDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="updatasava()">保存</el-button>
        <el-button
          type="primary"
          size="small"
          @click="submint(form.storageId)"
          style="margin-right: 10px"
          >提交</el-button
        >
      </template>

      <!-- 操作按钮 -->

      <!-- 子对话框 -->
      <delivery-notice-dialog
        v-model:visible="Eject.noticeDialogVisible"
        @select="handleNoticeSelect"
      />
      <supplier-dialog
        v-model:visible="Eject.supplierDialogVisible"
        @select="handleSupplierSelect"
      />

      <!-- 物料信息 -->
      <div style="margin-top: 80px">
        <el-link
          type="primary"
          size="small"
          @click="showmateriDialog()"
          style="margin-left: 20px"
          >新增</el-link
        >
        <el-table :data="maters" style="width: 100%; margin-top: 10px">
          <el-table-column type="序号" width="55" />
          <el-table-column  prop="materialnumber"  label="物料编码" width="120" />
          <el-table-column prop="materialname" label="物料名称" width="120" />
          <el-table-column prop="specification" label="规格型号" width="120" />
          <el-table-column prop="unit" label="单位" width="120" />
          <el-table-column prop="inboundNumber" label="入库数量" width="120" />
          <el-table-column prop="lotnumber" label="批次号" width="120" />

          <el-table-column label="操作" min-width="120">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                style="margin-right: 10px"
                @click="showShelves(form.storageId)"
                >上架</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { readaxios, writeaxios } from "@/https/axioshttps";
const apiUrl = import.meta.env.VITE_APP_API_URL;
import axios from "axios";
const tableData = ref([]);
onMounted(() => {
  getIncominginformation();
});

//清空
const empty = () => {
  (page.value.StorageNo = ""),
    (page.value.StorageName = ""),
    (page.value.StorageDate = null),
    (page.value.SupplierName = ""),
    (page.value.StoragePurchaseNo = ""),
    getIncominginformation();
};
// 显示入库信息
const getIncominginformation = () => {
  // 创建请求参数副本
  const params = {
    PageIndex: page.value.PageIndex,
    pageSize: page.value.PageSize,
    StorageNo: page.value.StorageNo || undefined,
    StorageName: page.value.StorageName || undefined,
    StorageDate: page.value.StorageDate || undefined,
    SupplierName: page.value.SupplierName || undefined,
  };
  axios
    .get(
      apiUrl+"/T5/Incominginformations/GetIncominginformations",
      {
        params,
      }
    )
    .then((res) => {
      tableData.value = res.data.data;
      page.value.totalCount = res.data.totalCount;
      page.value.totalPage = res.data.totalPage;
    });
};

// 新增、编辑
const Eject = reactive({
  dialogFormVisible: false, //新增弹出框
  noticeDialogVisible: false, //入库通知
  supplierDialogVisible: false, //供应商
  dialogupdataFormVisible: false, //修改弹出框
  materiDialogVisible: false, //物料
  ArrivalnoticematerVisible: false,
  title: "新增入库",
  formLabelWidth: "120px",
  dialogupdatacarryFormVisible: false, //执行入库修改弹出框
  Isture: true,
});

// const dialogVisible = ref(true);
const page = ref({
  PageIndex: 1,
  PageSize: 10,
  StorageNo: "",
  StorageName: "",
  StorageDate: null,
  SupplierName: "",
  StoragePurchaseNo: "",
  totalCount: 1,
  totalPage: 1,
});
// 主表单数据
const form = reactive({

  storageId: 0,
  storageNo: "",
  storageName: "",
  noticePurchase: 1,
  noticeId: 0,
  supplierId: 0,
  storageremark: "",
  storagePurchaseId: 0,
  storageDate:new Date(),
  isDlete: false,
  autoGenerate: false,
});

const showNoticeDialog = () => {
  Eject.noticeDialogVisible = true;
  selectedNoticeId.value = null; // 重置选中状态
  getnotices();
};

const showsupplierlog = () => {
  Eject.supplierDialogVisible = true;
  selectedSupplierId.value = null; // 重置选中状态
  getsuppliers();
};

// 用于存储选中的行
// 处理到货通知单选择
const handleNoticeSelect = (row: any) => {
  // 更新表单外键
  form.noticeId = row.noticeId;
  form.storagePurchaseId = row.storagePurchaseId;
  form.supplierId = row.supplierId;

  // 更新显示信息
  selectedNoticeInfo.noticeNo = row.noticeNo;
  selectedNoticeInfo.storagePurchaseNo = row.storagePurchaseNo;
  selectedNoticeInfo.supplierName = row.supplierName;

  // 关闭对话框前重置选择状态
  setTimeout(() => {
    Eject.noticeDialogVisible = false;
    selectedNoticeId.value = null; // 清除选中状态
  }, 100);
};

// 处理供应商选择
const handleSupplierSelect = (row: any) => {
  // 更新表单外键
  form.supplierId = row.supplierId;

  // 更新显示信息
  selectedNoticeInfo.supplierName = row.supplierName;

  // 关闭对话框前重置选择状态--延迟 100 毫秒执行代码
  setTimeout(() => {
    Eject.supplierDialogVisible = false;
    selectedSupplierId.value = null; // 清除选中状态
  }, 100);
};

// 自动生成编号逻辑
const generateNumber = () => {
  form.storageNo = `RK${Date.now()}`;
};

// 到货通知单表格数据

const emit = defineEmits(["update:visible", "select"]);

// 搜索表单
const searchForm = reactive({
  noticeNo: "",
  noticeName: "",
  storagePurchaseNo: "",
  supplierName: "",
  deliverydate: "",
  noticePurchase: null,
});

const noticeList = ref([]);
const getnotices = async () => {
  const search = {
    noticeNo: searchForm.noticeNo,
    noticeName: searchForm.noticeName,
    storagePurchaseNo: searchForm.storagePurchaseNo,
    supplierName: searchForm.supplierName,
    deliverydate: searchForm.deliverydate,
    noticePurchase: searchForm.noticePurchase,
  };
  await axios
    .get(apiUrl+"/T5/Incominginformations/GetArrivalnotice", {
      params: search,
    })
    .then((res) => {
      console.log(res.data.data);
      noticeList.value = res.data.data;
    });
};
// 生成入库编号
const generateCode = () => {
  const timestamp = Date.now(); // 获取精确到毫秒的时间戳
  form.storageNo = `RK${timestamp}`;
};

const handleSwitchChange = (val: boolean) => {
  form.autoGenerate = val;
  if (val) {
    generateCode(); // 开启自动生成时立即生成
  } else {
    form.storageNo = ""; // 关闭时清空编号
  }
};

const handleCodeClick = () => {
  if (form.autoGenerate) {
    generateCode(); // 点击输入框时重新生成
  }
};

/* // 反填字段类型不匹配
const fanTianZD = () => {};

// 单选功能实现
const selectedRow = ref(null); */

// 重置
const resetSearch = () => {
  Object.keys(searchForm).forEach((key: any) => {
    searchForm[key] = "";
  });
  searchForm.noticeNo = " ";
  searchForm.noticeName = " ";

  (searchForm.storagePurchaseNo = ""),
    (searchForm.supplierName = ""),
    (searchForm.deliverydate = ""),
    (searchForm.noticePurchase = null);

  getnotices();
};

//#region  供应商
// 供应商搜索框字段
const suppliers = reactive({
  SupplierNumber: "",
  SupplierName: "",
  SupplierAbbreviation: "",
  SupplierEnglishName: "",
  IsEnable: null,
});

const supplierList = ref([]);
const getsuppliers = async () => {
  axios
    .get("http://localhost:5056/api/Incominginformations/GetSupplier", {
      params: suppliers,
    })
    .then((res) => {
      supplierList.value = res.data.data;
    });
};

const selectedsupplierRow = ref(null);

// 重置供应商搜索数据
const resetsuppliersSearch = () => {
  (suppliers.SupplierNumber = ""),
    (suppliers.SupplierName = ""),
    (suppliers.SupplierAbbreviation = ""),
    (suppliers.SupplierEnglishName = ""),
    (suppliers.IsEnable = null),
    getsuppliers();
};
//#endregion

// 打开对应的弹出框
const open = (row: any) => {
  if (row == null) {
    Eject.dialogFormVisible = true;
    Eject.title = "新增入库信息";
    Eject.Isture = true;
    (form.storageId = 0),
      (form.storageNo = ""),
      (form.storageName = ""),
      (form.noticeId = 0),
      (form.storagePurchaseId = 0),
      (form.supplierId = 0),
      (form.storageremark = ""),
      (form.storageDate = new Date()); // 初始化为当前日期
    form.noticePurchase = null;
    selectedNoticeInfo.noticeNo = "";
    selectedNoticeInfo.storagePurchaseNo = "";
    selectedNoticeInfo.supplierName = "";
  } else {
    console.log(row, "88888");
    Eject.dialogupdataFormVisible = true;
    Eject.title = "修改入库信息";
    Eject.Isture = false;

    (form.storageId = row.storageId),
      (form.storageNo = row.storageNo),
      (form.storageName = row.storageName),
      (form.noticeId = row.noticeId);
    form.storagePurchaseId = row.storagePurchaseId;
    form.supplierId = row.supplierId;
    form.storageremark = row.storageremark;
    form.noticePurchase = row.noticePurchase;
    form.storageDate = row.storageDate; // 初始化为当前日期
    // selectedNoticeInfo.noticeNo = row.noticeNo;
    selectedNoticeInfo.storagePurchaseNo = row.storagePurchaseNo;
    selectedNoticeInfo.noticeNo = row.noticeNo;
    selectedNoticeInfo.supplierName = row.supplierName;
  }
};
// 新增、更新逻辑
const sava = async () => {
  // 组织提交数据（包含所有外键字段）
  const payload = {
    storageId: form.storageId,
    storageNo: form.storageNo,
    storageName: form.storageName,
    storageDate: form.storageDate, // 格式化为YYYY-MM-DD
    noticeId: form.noticeId,
    storagePurchaseId: form.storagePurchaseId,
    supplierId: form.supplierId,
    storageremark: form.storageremark,
  };
  if (form.storageNo == "") {
    ElMessage.error("请选择入库单编号");
    return;
  }
  if (form.storageName == "") {
    ElMessage.error("请选择入库单名称");
    return;
  }
  if (form.storageDate == null) {
    ElMessage.error("请选择入库日期");
    return;
  }
  console.log(payload, "payload");
  if (Eject.Isture) {
    axios
      .post(
        apiUrl+"/T6/Incominginformations/CreateIncominginformations",
        payload
      )
      .then((res) => {
        if (res.data.code == 100) {
          ElMessage.success(res.data.msg);
          Eject.dialogFormVisible = false;
          getIncominginformation();
          return;
        } else {
          ElMessage.error(res.data.msg);
          Object.assign(form, {
            storageId: 0,
            storageNo: "",
            storageName: "",
            noticeId: 0,
            storagePurchaseId: 0,
            supplierId: 0,
            storageremark: "",
            storageDate: new Date(),
          });

          Object.assign(selectedNoticeInfo, {
            noticeNo: "",
            storagePurchaseNo: "",
            supplierName: "",
          });
          getIncominginformation();
        }
      });
  } else {
   
  }
};

// 修改
const updatasava = () => {
  // 组织提交数据（包含所有外键字段）
  const payload = {
    storageId: form.storageId,
    storageNo: form.storageNo,
    storageName: form.storageName,
    storageDate: form.storageDate, // 格式化为YYYY-MM-DD
    noticeId: form.noticeId,
    storagePurchaseId: form.storagePurchaseId,
    supplierId: form.supplierId,
    storageremark: form.storageremark,
  };
 
  axios
    .put(
      apiUrl+"/T6/Incominginformations/UpdataIncominginformations",
      payload
    )
    .then((res) => {
      if (res.data.code == 206) {
        ElMessage.success(res.data.msg);
        Eject.dialogupdataFormVisible = false;
        getIncominginformation();
        return;
      } else {
        ElMessage.error(res.data.msg);
        Object.assign(form, {
          storageId: 0,
          storageNo: "",
          storageName: "",
          noticeId: 0,
          storagePurchaseId: 0,
          supplierId: 0,
          storageremark: "",
          storageDate: new Date(),
        });

        Object.assign(selectedNoticeInfo, {
          noticeNo: "",
          storagePurchaseNo: "",
          supplierName: "",
        });
        getIncominginformation();
      }
    });
};
// 分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  page.value.PageSize = val;
  getIncominginformation();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  page.value.PageIndex = val;
  getIncominginformation();
};

// 删除
const delIncoming = (StorageId: any) => {
  ElMessageBox.confirm("确认删除该入库单吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios
        .put(
        apiUrl+"/T6/Incominginformations/DelIncominginformations",
          { storageId: StorageId }
        )
        .then((res) => {
          if (res.data.code == 204) {
            ElMessage.success(res.data.msg);
            getIncominginformation();
          } else {
            ElMessage.error(res.data.msg);
          }
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

// 新增响应式对象存储关联信息
const selectedNoticeInfo = reactive({
  noticeId: 0,
  noticeNo: "",
  storagePurchaseId: 0,
  storagePurchaseNo: "",
  supplierId: 0,
  supplierName: "",
});

// 修复: 使用独立的状态变量存储选中ID
const selectedNoticeId = ref<number | null>(null);
const selectedSupplierId = ref<number | null>(null);
const selectedSupplierArrMateId = ref<number | null>(null);

//状态更新
const handleStockIn = async (
  storageId: any,
  noticeId: any,
  noticePurchase: any
) => {
  alert(storageId);
  try {
    const res = await axios.put(
      apiUrl+"/T6/Incominginformations/UpdataArrivalnoticeStatur",
      {
        storageId: storageId,
        noticeId: noticeId,
        noticePurchase: noticePurchase,
      }
    );

    if (res.data.code === 200) {
      // 局部更新数据
      // 局部更新当前行状态
      const index = tableData.value.findIndex(
        (item) => item.storageId == storageId
      );
      if (index > -1) {
        tableData.value[index].noticePurchase = 4;
      }
      ElMessage.success("入库成功");
     
    }
  } catch (error) {
    ElMessage.error("入库操作失败");
    console.error("入库错误:", error);
  }
};

// 导出入库信息
const GetExelRoomNumber = async () => {
  let url =apiUrl+`/T5/Incominginformations/ExeclIncomArriva`;

  window.location.href = url;
   getIncominginformation(); // 重新获取数据
};

// 导入入库信息
const ImportRoomNumber = async () => {
  console.log("执行导入操作");
  const input = document.createElement("input");
  input.type = "file";
  input.accept = ".csv, .xlsx"; // 可以根据实际需求修改允许的文件类型

  input.addEventListener("change", async (event) => {
    const file = event.target.files[0];
    if (file) {
      const formData = new FormData();
      formData.append("file", file);

      const url =
        apiUrl+"/T6/Incominginformations/ImportInventories";
      try {
        const response = await fetch(url, {
          method: "POST",
          body: formData,
        });
        if (response.ok) {
          ElMessage.success("导入成功");
          getIncominginformation();
        }

        if (!response.ok) {
          throw new Error(`请求失败，状态码: ${response.status}`);
        }

        const result = await response.json();
        console.log("导入成功，返回结果:", result);
      } catch (error) {
        console.error("导入失败:", error);
      }
    }
  });

  input.click();
};

//#region    物料入库

const formData = ref({
  materialnumber: "",
  materialname: "",
  unit: 0,
  inboundNumber: 0,
  validityDate: "",
  lotnumber: "",
  sTime: "",
  remark: "",
});

const showmaterialOptions = () => {
  Eject.ArrivalnoticematerVisible = true;
  selectedSupplierArrMateId.value = null; // 清空选择中状态
  getmaterArrivas();
};

// 到货通知单选择
const materArriva = ref([]);
const getmaterArrivas = () => {
  axios
    .get(apiUrl+"/T5/Incominginformations/GetMateArriva")
    .then((res) => {
      console.log(res.data.data,'66767');
      materArriva.value = res.data.data;
    });
};

// 新增到货通知单选择
const selectedArrMaterInfo = reactive({});

//控制物料入库单行弹出框
// 处理到货通知单选择(采购入库)选择
const handleArrivalnoticematerSelect = (row: any) => {
  sessionStorage.setItem("selectedProductionTask", JSON.stringify(row));

  const selectedTaskData = sessionStorage.getItem("selectedProductionTask");
  console.log("从 sessionStorage 中获取选中的生产任务数据", selectedTaskData);
  if (selectedTaskData) {
    const task = JSON.parse(selectedTaskData);
    console.log("解析后的生产任务数据", task);
    formData.value.materialnumber = task.materialnumber;
    formData.value.materialname = task.materialname;
    formData.value.unit = task.unit;
    formData.value.remark = task.remark;
  } else {
    //  console.log('sessionStorage 中没有选中的生产任务数据');
  }

  // 关闭对话框前重置选择状态--延迟 100 毫秒执行代码
  setTimeout(() => {
    Eject.ArrivalnoticematerVisible = false;
    selectedSupplierArrMateId.value = null; // 清除选中状态
  }, 100);
};

// 新增物料入库单行
const handleConfirm = () => {
  axios
    .post(apiUrl+"/T6/Incominginformations/CreateMaterialmanagement",
      formData.value
    )
    .then((res) => {
      if (res.data.code === 100) {
        ElMessage.success("新增成功");
        Eject.materiDialogVisible = false;
         // 从sessionStorage获取最新数据
        const savedData = sessionStorage.getItem('selectedProductionTask');
      console.log("从 sessionStorage 中获取选中的生产任务数据1111111111", savedData);
      if (savedData) {
        const newItem = JSON.parse(savedData);
        console.log("解析后的生产任务数据--222222", newItem);
        // 推送到maters数组
        maters.push({
          materialnumber: newItem.materialnumber,
          materialname: newItem.materialname,
          specification: newItem.specification,    // 根据实际情况获取
          unit: newItem.unit,
          inboundNumber: newItem.inboundNumber,
          
          noticeNumber: newItem.noticeNumber,
          lotnumber: newItem.lotnumber
        });
      }

      // 清空表单
      formData.value = { 
        materialnumber: '',
        materialname: '',
        unit: 0,
        inboundNumber: 0,
        validityDate: '',
        lotnumber: '',
        sTime: '',
        remark: ''
      };
        
         getmater();
      } else {
        ElMessage.error("新增失败");
        // 重置
        (formData.value.materialnumber = ""),
          (formData.value.materialname = ""),
          (formData.value.unit = 0),
          (formData.value.inboundNumber = 0),
          (formData.value.validityDate = ""),
          (formData.value.lotnumber = ""),
          (formData.value.sTime = ""),
          (formData.value.remark = "");
      }
    });
};
const maters = reactive<any>([{
  materialnumber: "",
  materialname: "",
  unit: 0,
  inboundNumber: 0,
  validityDate: "",
  lotnumber: "",
  sTime: "",
  remark: "",

}]);
const getmater = () => {
  
     const selectedTaskData = sessionStorage.getItem('selectedProductionTask');
  if (selectedTaskData) {
    const task = JSON.parse(selectedTaskData);
console.log(task,"task");
    // 清除旧数据
     maters.splice(0, maters.length);

    // 添加新数据到数组
    maters.push({
      materialnumber: task.materialnumber,
      materialname: task.materialname,
      specification: task.specification,    // 根据实际情况获取
      unit: task.unit,
      inboundNumber: task.inboundNumber,
      noticeNumber: task.noticeNumber,
      lotnumber: task.lotnumber
    });
  }

};
 console.log('生产任务字段已反填2222223333333:',   maters.materialnumber);
const showmateriDialog = () => {
  Eject.materiDialogVisible = true;
};

const submint = (storageId: any) => {
  Eject.dialogupdataFormVisible = false;
  axios
    .put(
      apiUrl+"/T6/Incominginformations/UpdataArrivalnoticeStaturs",
      { storageId: storageId }
    )
    .then((res) => {
      if (res.data.code === 206) {
        ElMessage.success("状态更新成功");
        getIncominginformation();
      } else {
        ElMessage.error("状态更新失败");
      }
    });
};

// 执行入库
const executeInventory = () => {
  // updatasava();
  getmater();
  Eject.dialogupdatacarryFormVisible = true;
};

// 上架
const showShelves = (storageId: any) => {
  shelfInventory(storageId);
  Eject.dialogupdatacarryFormVisible = false;
};

const shelfInventory = (storageId: any) => {
  axios
    .put(
     apiUrl+"/T6/Incominginformations/UpdataArrivalnoticeStaturs",
      { storageId: storageId }
    )
    .then((res) => {
      if (res.data.code === 206) {
        ElMessage.success("状态更新成功");
        getIncominginformation();
      } else {
        ElMessage.error("状态更新失败");
      }
    });
};
//#endregion   物料入库
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
.el-form-item {
  margin-right: 15px;
  margin-bottom: 10px;
}
</style>